package com.pivotal.cloud.crypto.encrypt;

import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;

import java.io.InputStream;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyStore;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.interfaces.RSAPrivateCrtKey;
import java.security.spec.RSAPublicKeySpec;

/**
 * @className: com.pivotal.cloud.security.crypto.encrypt.KeyStoreKeyFactory
 * @projectName: PivotalCloud项目
 * @module: PivotalCloud项目-KeyStoreKeyFactory类，主要位于Security安全模块-Key存储工厂模块
 * @content: KeyStoreKeyFactory-Key存储工厂
 * @author: Powered by Marklin
 * @datetime: 2025-06-25 23:06
 * @version: 1.0.0
 * @copyright: Copyright © 2018-2025 PivotalCloud Systems Incorporated. All rights
 * reserved.
 */
public class KeyStoreKeyFactory {

	private final Resource resource;

	private final char[] password;

	private KeyStore store;

	private final Object lock = new Object();

	private final String type;

	public KeyStoreKeyFactory(Resource resource, char[] password) {
		this(resource, password, type(resource));
	}

	private static String type(Resource resource) {
		String ext = StringUtils.getFilenameExtension(resource.getFilename());
		return (ext != null) ? ext : "jks";
	}

	public KeyStoreKeyFactory(Resource resource, char[] password, String type) {
		this.resource = resource;
		this.password = password;
		this.type = type;
	}

	public KeyPair getKeyPair(String alias) {
		return getKeyPair(alias, this.password);
	}

	public KeyPair getKeyPair(String alias, char[] password) {
		try {
			synchronized (this.lock) {
				if (this.store == null) {
					synchronized (this.lock) {
						this.store = KeyStore.getInstance(this.type);
						try (InputStream stream = this.resource.getInputStream()) {
							this.store.load(stream, this.password);
						}
					}
				}
			}
			RSAPrivateCrtKey key = (RSAPrivateCrtKey) this.store.getKey(alias, password);
			Certificate certificate = this.store.getCertificate(alias);
			PublicKey publicKey = null;
			if (certificate != null) {
				publicKey = certificate.getPublicKey();
			}
			else if (key != null) {
				RSAPublicKeySpec spec = new RSAPublicKeySpec(key.getModulus(), key.getPublicExponent());
				publicKey = KeyFactory.getInstance("RSA").generatePublic(spec);
			}
			return new KeyPair(publicKey, key);
		}
		catch (Exception ex) {
			throw new IllegalStateException("Cannot load keys from store: " + this.resource, ex);
		}
	}

}
